package com.hupu.jrs.ui.thread.list

import android.app.Activity
import android.net.Uri
import android.os.Bundle
import android.support.design.widget.AppBarLayout
import android.support.design.widget.CollapsingToolbarLayout
import android.support.design.widget.Snackbar
import android.support.v4.view.MenuItemCompat
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.SearchView
import android.support.v7.widget.Toolbar
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.drawee.view.SimpleDraweeView
import com.facebook.imagepipeline.common.ResizeOptions
import com.facebook.imagepipeline.request.ImageRequestBuilder
import com.github.clans.fab.FloatingActionButton
import com.github.clans.fab.FloatingActionMenu
import javax.inject.Inject
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.hupu.jrs.R
import com.hupu.jrs.ui.BaseFragment
import com.hupu.jrs.ui.login.LoginActivity
import com.hupu.jrs.ui.post.PostActivity
import com.hupu.jrs.ui.thread.ThreadListAdapter
import com.hupu.jrs.util.ResourceUtil
import com.hupu.jrs.util.SettingPrefUtil
import com.hupu.jrs.widget.LoadMoreRecyclerView

/**
 * Created by sll on 2016/3/9.
 */
class ThreadListFragment : BaseFragment(), ThreadListContract.View, SwipeRefreshLayout.OnRefreshListener, AppBarLayout.OnOffsetChangedListener, LoadMoreRecyclerView.LoadMoreListener {


    @Inject
    internal var mPresenter: ThreadListPresenter? = null
    @Inject
    internal var mAdapter: ThreadListAdapter? = null
    @Inject
    internal var mActivity: Activity? = null

    @BindView(R.id.backdrop)
    internal var backdrop: SimpleDraweeView? = null
    @BindView(R.id.tvSubTitle)
    internal var tvSubTitle: TextView? = null
    @BindView(R.id.toolbar)
    internal var toolbar: Toolbar? = null
    @BindView(R.id.collapsing_toolbar)
    internal var collapsingToolbar: CollapsingToolbarLayout? = null
    @BindView(R.id.appbar)
    internal var appbar: AppBarLayout? = null
    @BindView(R.id.recyclerView)
    internal var recyclerView: LoadMoreRecyclerView? = null
    @BindView(R.id.refreshLayout)
    internal var refreshLayout: SwipeRefreshLayout? = null
    @BindView(R.id.floatingAttention)
    internal var floatingAttention: FloatingActionButton? = null
    @BindView(R.id.floatingPost)
    internal var floatingPost: FloatingActionButton? = null
    @BindView(R.id.floatingSwitch)
    internal var floatingSwitch: FloatingActionButton? = null
    @BindView(R.id.floatingRefresh)
    internal var floatingRefresh: FloatingActionButton? = null
    @BindView(R.id.floatingMenu)
    internal var floatingMenu: FloatingActionMenu? = null
    @BindView(R.id.frameLayout)
    internal var frameLayout: FrameLayout? = null

    fun onCreateView(inflater: LayoutInflater, container: ViewGroup,
                     savedInstanceState: Bundle): View {
        setHasOptionsMenu(true)
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    fun initInjector() {
        getComponent(ThreadListComponent::class.java).inject(this)
    }

    fun initContentView(): Int {
        return R.layout.fragment_thread
    }

    fun getBundle(bundle: Bundle) {

    }

    fun initUI(view: View) {
        ButterKnife.bind(this, view)
        mPresenter!!.attachView(this)
        (mActivity as ThreadListActivity).initToolBar(toolbar)
        initFloatingButton()
        attachPostButtonToRecycle()
        refreshLayout!!.setOnRefreshListener(this)
        appbar!!.addOnOffsetChangedListener(this)
        val layoutManager = LinearLayoutManager(mActivity!!.applicationContext)
        recyclerView!!.setLayoutManager(layoutManager)
        recyclerView!!.setHasFixedSize(true)
        recyclerView!!.setAdapter(mAdapter)
        recyclerView!!.setLoadMoreListener(this)
    }

    private fun initFloatingButton() {
        ResourceUtil.setFabBtnColor(mActivity, floatingPost)
        ResourceUtil.setFabBtnColor(mActivity, floatingSwitch)
        ResourceUtil.setFabBtnColor(mActivity, floatingRefresh)
        ResourceUtil.setFabBtnColor(mActivity, floatingAttention)
        ResourceUtil.setFabMenuColor(mActivity, floatingMenu)
        if (SettingPrefUtil.getThreadSort(mActivity).equals(Constants.THREAD_TYPE_HOT)) {
            floatingSwitch!!.labelText = "按发帖时间排序"
        } else {
            floatingSwitch!!.labelText = "按回帖时间排序"
        }
    }

    private fun attachPostButtonToRecycle() {
        recyclerView!!.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                if (Math.abs(dy) > 4) {
                    if (dy > 0) {
                        floatingMenu!!.hideMenuButton(true)
                    } else {
                        floatingMenu!!.showMenuButton(true)
                    }
                }
            }
        })
    }

    fun initData() {
        mPresenter!!.onThreadReceive(SettingPrefUtil.getThreadSort(mActivity))
    }

    override fun showLoading() {
        refreshLayout!!.postDelayed({ refreshLayout!!.isRefreshing = true }, 5)
    }

    override fun showProgress() {
        showProgress(true)
    }

    override fun showContent() {
        showContent(true)
    }

    override fun renderThreadInfo(forum: Forum) {
        val request = ImageRequestBuilder.newBuilderWithSource(Uri.parse(forum.getBackImg()))
                .setResizeOptions(ResizeOptions(500, 500))
                .build()
        val draweeController = Fresco.newDraweeControllerBuilder()
                .setImageRequest(request)
                .setOldController(backdrop!!.controller)
                .setAutoPlayAnimations(true)
                .build()
        backdrop!!.controller = draweeController
        collapsingToolbar!!.title = forum.getName()
        tvSubTitle!!.setText(forum.getDescription())
    }

    override fun renderThreads(threads: List<Thread>) {
        mAdapter!!.bind(threads)
        recyclerView!!.getAdapter().notifyDataSetChanged()
    }

    override fun onLoadCompleted(hasMore: Boolean) {
        recyclerView!!.onLoadCompleted(hasMore)
    }

    override fun onRefreshCompleted() {
        refreshLayout!!.isRefreshing = false
    }

    override fun attendStatus(isAttention: Boolean) {
        if (!isAttention) {
            floatingAttention!!.setImageResource(R.drawable.ic_menu_add)
            floatingAttention!!.labelText = "添加关注"
        } else {
            floatingAttention!!.setImageResource(R.drawable.ic_minus)
            floatingAttention!!.labelText = "取消关注"
        }
    }

    override fun onError(error: String) {
        setErrorText(error)
        showError(true)
    }

    override fun onEmpty() {
        setEmptyText("暂无帖子")
        showEmpty(true)
    }

    override fun onScrollToTop() {
        recyclerView!!.smoothScrollToPosition(0)
    }

    override fun onFloatingVisibility(visibility: Int) {
        floatingMenu!!.visibility = visibility
    }

    override fun showPostThreadUi(fid: String) {
        PostActivity.startActivity(mActivity, Constants.TYPE_POST, fid, "", "", "")
    }

    override fun showLoginUi() {
        LoginActivity.startActivity(mActivity)
    }

    override fun showToast(msg: String) {
        Snackbar.make(getView(), msg, Snackbar.LENGTH_SHORT).show()
    }

    override fun onOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) {
        if (verticalOffset == 0 || verticalOffset == -appBarLayout.totalScrollRange) {
            refreshLayout!!.isEnabled = true
        } else {
            refreshLayout!!.isEnabled = false
        }
    }

    override fun onRefresh() {
        mPresenter!!.onRefresh()
    }

    fun onReloadClicked() {
        mPresenter!!.onReload()
    }

    @OnClick(R.id.floatingAttention)
    internal fun floatingAttention() {
        mPresenter!!.onAttentionClick()
        floatingMenu!!.toggle(true)
    }

    @OnClick(R.id.floatingPost)
    internal fun floatingPost() {
        mPresenter!!.onPostClick()
        floatingMenu!!.toggle(true)
    }

    @OnClick(R.id.floatingRefresh)
    internal fun floatingRefresh() {
        mPresenter!!.onRefresh()
        floatingMenu!!.toggle(true)
    }

    @OnClick(R.id.floatingSwitch)
    internal fun floatingSwitch() {
        if (floatingSwitch!!.labelText == "按回帖时间排序") {
            mPresenter!!.onThreadReceive(Constants.THREAD_TYPE_HOT)
            floatingSwitch!!.labelText = "按发帖时间排序"
        } else {
            mPresenter!!.onThreadReceive(Constants.THREAD_TYPE_NEW)
            floatingSwitch!!.labelText = "按回帖时间排序"
        }
        floatingMenu!!.toggleMenuButton(true)
    }

    fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.menu_thread, menu)
        val menuItem = menu.findItem(R.id.action_search)//在菜单中找到对应控件的item
        val searchView = MenuItemCompat.getActionView(menuItem) as SearchView
        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String): Boolean {
                mPresenter!!.onStartSearch(query, 1)
                return false
            }

            override fun onQueryTextChange(newText: String): Boolean {
                return false
            }
        })
        MenuItemCompat.setOnActionExpandListener(menuItem,
                object : MenuItemCompat.OnActionExpandListener {
                    //设置打开关闭动作监听
                    override fun onMenuItemActionExpand(item: MenuItem): Boolean {
                        return true
                    }

                    override fun onMenuItemActionCollapse(item: MenuItem): Boolean {
                        mPresenter!!.onThreadReceive(SettingPrefUtil.getThreadSort(mActivity))
                        return true
                    }
                })
    }

    fun onDestroy() {
        super.onDestroy()
        mPresenter!!.detachView()
    }

    fun onLoadMore() {
        mPresenter!!.onLoadMore()
    }
}
